//standard send service
define(["angularAMD"], function (angularAMD) {
	// register
	angularAMD.service("WebService", function($http, $state, $rootScope, config){
		var server = config.server;
		var targetIP = '127.0.0.1';
		
		function send(httpData, showLoading) {
			if(showLoading == undefined)
				showLoading = true;
			
			if(showLoading)
				$rootScope.showLoading();
			
			$http(httpData.data).success(function(data, status, headers, config) {
				if(showLoading)
					$rootScope.hideLoading();
				
				if(data.errorMsg != 'sessionTimeOut'){
					if(httpData.success != undefined){
						httpData.success(data, status, headers, config);
					}
				} else {
					$rootScope.showAlert("Can't connect KMI Server.", function(){
						$state.go('login');
					});
				}
			}).error(function(a,b,c,d){
				if(showLoading)
					$rootScope.hideLoading();
				
				if(httpData.error != undefined){
					httpData.error(a, b, c, d);
				} else {
					$rootScope.showAlert("連線發生錯誤.", function(){
						send(httpData, showLoading);
					});
				}
			});
		}
		
		this.sendToServer = function(sendData, showLoading) {
			var httpData = {
				data : {
					url : 'http://'+server.ip+':'+server.port+'/'+server.name+'/'+sendData.url,
					method : 'POST',
					withCredentials : true, //允許跨網域
					headers : {
						'Content-Type': 'application/json;charset=UTF-8'
					},
					data : sendData.data
				},
				success : sendData.success,
				error : sendData.error
			};
			send(httpData, showLoading);
		}
		
		this.sendToWA = function(targetURL, sendData, showLoading){
			var httpData = {
				data : {
				    url : targetURL,
				    method : 'POST',
				    headers : {
				    	'Content-Type': 'application/json;charset=UTF-8',
				    	Authorization: 'Basic YWRtaW46'
				    },
			        data : sendData.data
				},
				success : sendData.success,
				error : sendData.error
			};
			send(httpData, showLoading);
		}

		this.send = function(httpData, showLoading){
			send(httpData, showLoading);
		}
	});
});